home *** CD-ROM | disk | FTP | other *** search
/ The Very Best of Atari Inside / The Very Best of Atari Inside 1.iso / mint / mntlb20 / lib / tmpfile.c < prev    next >
C/C++ Source or Header  |  1991-11-10  |  2KB  |  81 lines

  1. /* tmpfile.c: create a temporary file that will be deleted when exit()
  2.    is called.
  3.    Written by Eric R. Smith and placed in the public domain.
  4. */
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8.  
  9. extern int __mint;
  10.  
  11. typedef struct {
  12.     char    *name;
  13.     FILE    *fp;
  14. } FILE_RECORD;
  15.  
  16. static FILE_RECORD    *file_to_delete;
  17. static int        numtmps = -1;
  18.  
  19. static void
  20. delete_tmpfiles()
  21. {
  22.     int i;
  23.  
  24.     for (i = 0; i <= numtmps; i++)
  25.     {
  26.         fclose(file_to_delete[i].fp);
  27.         remove(file_to_delete[i].name);
  28.     }
  29. }
  30.  
  31. FILE *tmpfile()
  32. {
  33.     char *junknam;
  34.     FILE *junkfil;
  35.  
  36.     if ( !(junknam = tmpnam(NULL)) || !(junkfil = fopen(junknam, "w+b")) )
  37.     {
  38.         if(junknam)
  39.             free(junknam);
  40.         return NULL;
  41.     }
  42.  
  43. /* in MiNT 0.9 and above, we can often unlink a file and continue to use
  44.  * it; some file systems may return EACCDN for unlinking an open file,
  45.  * in which case we use the old method of unlinking the file at exit
  46.  */
  47.     if (__mint >= 9) {
  48.         if (remove(junknam) == 0)
  49.             return junkfil;
  50.     }
  51.  
  52.     if((++numtmps) == 0)
  53.         file_to_delete = (FILE_RECORD *)malloc((size_t)sizeof(FILE_RECORD));
  54.     else
  55.         file_to_delete = (FILE_RECORD *)realloc(file_to_delete,
  56.                     (size_t)((numtmps+1) * sizeof(FILE_RECORD)));
  57.     if(file_to_delete == (FILE_RECORD *)NULL)
  58.     {
  59.         fclose(junkfil);
  60.         remove(junknam);
  61.         free(junknam);
  62.         numtmps -= 1;
  63.         return NULL;    /* outa mem */
  64.     }
  65. /* install this in the list of temporary files to be deleted at exit */
  66.     file_to_delete[numtmps].name = junknam;
  67.     file_to_delete[numtmps].fp   = junkfil;
  68.  
  69. /* if this is the first, install the delete routine */
  70.     if (numtmps == 0)
  71.         if(atexit(delete_tmpfiles) != 0)
  72.         {    /* atexit failed -- cleanup */
  73.             delete_tmpfiles();
  74.             numtmps = -1;
  75.             free(file_to_delete[0].name);
  76.             free(file_to_delete);
  77.             return NULL;
  78.         }
  79.     return junkfil;
  80. }
  81.